<?php

namespace app\api\controller;

use addons\epay\controller\Api;
use app\api\service\PayService;
use think\Db;

use think\Exception;
use Yansongda\Pay\Log;
use Yansongda\Pay\Pay;

class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function notify()
    {
         $raw_post_data =  isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA']:file_get_contents("php://input");
         if(!$raw_post_data){
             exit('付款失败！');
         }
         //将XML转换成数组   禁止引用外部xml实体
         libxml_disable_entity_loader(true);
         $array_data = json_decode(json_encode(simplexml_load_string($raw_post_data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
         unset($array_data['sign']);
         if ($array_data['result_code'] == 'SUCCESS' && $array_data['return_code'] == 'SUCCESS') {
             $str = $array_data['out_trade_no'];//订单号
        $order = Db::name('order')->where('order_sn', $str)->find();
          if($order['order_status']>=2){
              exit('该订单已支付！');
          }
        Db::startTrans();
        try {
            $rs = Db::name('order')->where('order_sn', $str)->update(['order_status' => 2]);
            if ($order['goods_type'] == 3) {
                Db::name('user')->where('id', $order['user_id'])->update(['level' => 2]);
            } elseif ($order['goods_type'] == 1) {
                //增加业绩并更新等级
                $this->addPerformance($order['user_id'], $order['total_amount']);
                $user = Db::name('user')->where('id', $order['user_id'])->find();
                //直推奖
                if ($user['pid']) {
                    $this->handOutPrizes($user['pid'], $order['total_amount']);
                    //团队奖
                    $p_user = Db::name('user')->where('id', $user['pid'])->find();
                        $this->teamPrizes($user['pid'], $user['level'], $order['total_amount']);
                }
                //区域奖
                $address = Db::name('user_address')->where('address_id', $order['address_id'])->find();
                $where = [];
                $where['province'] = $address['province'];
                $where['city'] = $address['city'];
                $where['area'] = $address['area'];
                $where['status'] = 1;
                $partner = Db::name('partner')->where($where)->find();
                if ($partner) {
                    $this->regionalAward($partner['user_id'], $order['total_amount']);
                }
                //加权分红
                $this->dividend($order['total_amount']);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            exit($e->getMessage());
        }
        exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA]></return_msg></xml>');
        }else{
            exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA]></return_msg></xml>');
        }
    }

    //递归增加业绩
    public function addPerformance($user_id, $price)
    {
        $user = Db::name('user')->where('id', $user_id)->find();
        $total_invests=bcadd($user['total_invest'],$price,2);
        $id= Db::name('user')->where('id', $user_id)->update(['total_invest'=>$total_invests]);
        $this->updateLevel($user['id'], $user['level'], $user['referrals'], $total_invests);
        if ($user['pid']) {
            $this->addPerformance($user['pid'], $price);
        }
    }

    //更新用户等级
    public function updateLevel($user_id, $level, $referrals, $total_invest)
    {
        $update_level=1;
        if ($level == 1) {
            if ($referrals >= 10 && $total_invest >= 10000) {
                $update_level = 2;
            } else {
                $update_level = $level;
            }
        } elseif ($level == 2) {
            if ($referrals >= 50 && $total_invest >= 1000000) {
                $update_level = 3;
            } else {
                $update_level = $level;
            }
        }
        if ($level != $update_level) {
            $rs = Db::name('user')->where('id', $user_id)->setField('level', $update_level);
            if ($rs) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    //直推奖发放
    public function handOutPrizes($user_id, $price)
    {
        $user = Db::name('user')->where('id', $user_id)->find();
        if ($user['level'] == 1) {
            $scale = config('site.vip_scale');
        } elseif ($user['level'] == 2 && $user['is_partner'] == 2) {
            $scale = config('site.distributor_scale');
        } elseif ($user['level'] == 2 && $user['is_partner'] == 1) {
            $scale = config('site.partner_scale');
        } elseif ($user['level'] == 3) {
            $scale = config('site.stockholder_scale');
        }
        $scales = bcdiv($scale, 100, 2);
        $bonus = bcmul($price, $scales, 2);
        $total_score = bcadd($user['score'], $bonus, 2);
        $rs = Db::name('user')->where('id', $user_id)->update(['score' => $total_score]);
        if ($rs) {
            add_score_log($user_id, $bonus, $user['score'], $total_score, '直推奖', 1);
            return true;
        } else {
            return false;
        }
    }
    //区域奖
    public function regionalAward($user_id,$price){
        $user = Db::name('user')->where('id', $user_id)->find();
        $scale = config('site.partner_region_scale');
        $scales = bcdiv($scale, 100, 2);
        $bonus = bcmul($price, $scales, 2);
        $total_score = bcadd($user['score'], $bonus, 2);
        $rs = Db::name('user')->where('id', $user_id)->update(['score' => $total_score]);
        if ($rs) {
            add_score_log($user_id, $bonus, $user['score'], $total_score, '区域奖', 1);
            return true;
        } else {
            return false;
        }
    }
    //加权分红
    public function dividend($price){
        $scale = config('site.stockholder_dividend_scale');
        $scales = bcdiv($scale, 100, 2);
        $bonus = bcmul($price, $scales, 2);
        $dividend=Db::name('user')->where(['level'=>3])->select();
        $num=count($dividend);
        if($num){
            $amount=bcdiv($bonus,$num,2);
            foreach ($dividend as $k=>$v){
                $total_score= bcadd($v['score'],$amount,2);
                Db::name('user')->where('id', $v['id'])->update(['score' => $total_score]);
                add_score_log($v['id'], $amount, $v['score'], $total_score, '加权分红', 1);
            }
        }

        return true;
    }
    //团队奖
    public function teamPrizes($pid, $level,$price)
    {
        $user = Db::name('user')->where('id', $pid)->find();
        if($user['level']>=2){
            if($user['level']!=$level) {
                if ($user['level'] == 2) {
                    $scale = config('site.distributor_team_scale');
                } else if ($user['level'] == 3) {
                    $scale = config('site.stockholder_team_scale');
                }
                $scales = bcdiv($scale, 100, 2);
                $bonus = bcmul($price, $scales, 2);
            }else if($user['level']==$level){
                if($user['level']==2){
                    $scale = config('site.distributor_grade_scale');
                    $scale1 = config('site.distributor_grade_scale');
                }else if($user['level']==3){
                    $scale = config('site.stockholder_grade_scale');
                    $scale1 = config('site.distributor_grade_scale');
                }
                $scales = bcdiv($scale, 100, 2);
                $scales1= bcdiv($scale1, 100, 2);
                $bonus = bcmul($price, $scales, 2);
                $bonus=bcmul($bonus, $scales1, 2);
            }
            $total_score = bcadd($user['score'], $bonus, 2);
            $rs = Db::name('user')->where('id', $pid)->update(['score' => $total_score]);
            if ($rs) {
                add_score_log($pid, $bonus, $user['score'], $total_score, '团队奖', 1);
            }
            $price=$bonus;
        }
        if($price>=0.1 && $user['pid']){
            $this->teamPrizes($user['pid'],$user['level'],$price);
        }
    }
}